<template>
	<view class="top-cont">

	</view>
	<view class="bg-white nav justify-between flex">
		<text class="cu-item cuIcon-back text-lg text-grey" @click="onBack"></text>
		<view class="margin-left-xl">
			<view class="cu-item " :class="actIdx==0?'text-black cur':''" @click="actIdx=0">图文</view>
			<view class="cu-item " :class="actIdx==1?'text-black cur':''" @click="actIdx=1">音乐</view>
		</view>
		<text class="next-btn text-blue cu-item" @click="onNext">下一步</text>
	</view>

	<!-- 内容区 -->
	<view class="content">
		<view class="tab-content " v-if="actIdx==0">
			<!-- 添加图片 -->
			<view class="img-cont flex justify-center ">
				<view class="image-upload">
					<image class="upload-placeholder" :src="form.image" v-if="form.image" mode="aspectFill"></image>
					<view class="upload-placeholder text-center" v-else @click="chooseImage">
						+添加图片（可无）
					</view>
				</view>
			</view>
			<view class="draft-box" @click="openDraft">
				<text class="cuIcon-text"></text> 草稿箱
			</view>

			<!-- 表单区域 -->
			<form class="margin-top form-item">
				<!-- 标题 -->
				<input class="input text-center text-grey" v-model="input.title" placeholder="标题（可无）"
					placeholder-style="color:#BEBDC2" @blur="handleEmit" @confirm="handleEmit" />
				<view class="divider cont" />
				<!-- 正文 -->
				<textarea adjust-position class="textarea" v-model="input.content" placeholder="正文"
					placeholder-style="color:#BEBDC2" @blur="handleEmit" @confirm="handleEmit"></textarea>
				<view class="divider cont" />
				<!-- 出处/作者 -->
				<input class="input text-center text-grey" v-model="input.author" placeholder="出处/作者（可无）"
					placeholder-style="color:#BEBDC2" @blur="handleEmit" @confirm="handleEmit" />
				<view class="divider-cont">

				</view>
				<!-- 分类选择 -->
				<view class="flex padding-sm">
					<view class="category-title align-center flex  ">
						选择分类：
					</view>
					<view class="category-group align-center">
						<text class="category-tag " :class="{ active: form.category === item }"
							@click="form.category = item" v-for="item in categories" :key="item">
							{{ item }}
						</text>
					</view>
				</view>
				<view class="divider" />

				<!-- 原创开关 -->
				<view class="form-item switch-item">
					<text class="padding-left-sm ">我是原创：</text>
					<switch class="margin-right-xl" color="#007AFF" @change="form.isOriginal=!form.isOriginal" />
				</view>
				<view class="divider" />
				<!-- 私密开关 -->
				<view class="form-item switch-item  margin-bottom-xs">
					<text class="padding-left-sm ">私密：</text>
					<switch class="margin-right-xl " color="#007AFF" @change="form.isPrivate=!form.isPrivate" />

				</view>
				<view class="divider-cont big  flex justify-end align-center">
					<text class="padding-xs padding-right-xl " v-if="form.isPrivate">仅自己可见</text>
					<text class="padding-xs padding-right-xl " v-else>所有人可见</text>
				</view>
				<!-- 存入文集 -->
				<view class="flex align-center justify-between " style="height: 90upx;" @click="">
					<text class=" padding-left-sm">存入文集：</text>
					<view class="form-item">
						<!-- <picker mode="selector" :range="collections" @change="onCollectionChange">
							<view class="picker-view">
								{{ form.titlename || '请选择文集' }}
								<text class="cuIcon-right"></text>
							</view>
						</picker> -->

						<view class="">
							<view class="margin-right-xl" @click="open">
								<view class="flex justify-center align-center">
									<image class="margin-right" :src="img" mode="" style="width: 60upx; height: 60upx;"></image>
									<text> {{ form.titlename || '请选择文集' }}</text>
									<text class="cuIcon-right"></text>
								</view>
							</view>
							<uni-popup ref="popupRef" type="bottom" border-radius="10px 10px 0 0">
								<!-- 弹窗内容 -->
								<view class="flex flex-wrap bg-white padding-bottom-xl" style="border-radius: 20upx;">
									<view v-for="(item,index) in counter.collectedWorks" :id="item.objectId" :style="{ 
										backgroundImage: `url(${item.picture})`,
										backgroundSize: 'cover', 
										backgroundPosition: 'center center',
										filter: 'brightness(0.9)',
										border: form.objectId === item.objectId ? '2px solid #007AFF' : 'none'
									}" class="literature margin text-center" @click="onCollectionChange(index,item.picture)">
										<text class="text-bold text-lg"
											:class="item.picture?'text-white':''">{{item.titlename}}</text>
										<view class="text-sm">{{item.optionalrange}}</view>
									</view>
								</view>
							</uni-popup>
						</view>



					</view>
				</view>

			</form>
		</view>

		<!-- 音乐  -->
		<view class="tab-content" v-else>
			<view class="music-upload">
				<text class="cuIcon-musiclist"></text>
				<text class="upload-tip">+添加音乐（可无）</text>
			</view>
			<view class="form-item flex align-center">
				<input class="input text-center text-grey" placeholder="音乐标题（可无）" placeholder-style="color:#BEBDC2" />
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { type Ref, ref, computed } from 'vue';
	import type { Post } from '@/model/goods';
	import { createGoods } from '@/api/createGoods_api'
	import { useCounterStore } from '@/store/counter';
	import { onShow } from '@dcloudio/uni-app';
	import http from '@/utils/http';

	// 创建 ref 关联弹窗组件
	const popupRef = ref<any>(null); // 用 any 类型兼容组件实例
	// 打开弹窗
	const open = () => {
		popupRef.value.open('bottom')
	}
	// 关闭弹窗
	const close = () => {
		// 调用组件的 close 方法
		popupRef.value?.close();
	};
	//开启状态机
	const counter = useCounterStore()
	// 状态
	const actIdx : Ref<number> = ref(0)
	const tab = ref<'图文' | '音乐'>('图文');
	const form = ref<Post>({
		image: '',
		title: '',
		content: '',
		author: '',
		category: '文字',
		isOriginal: false,
		isPrivate: false,
		favorites: 0,
		comments: 0,
		likes: 0,
		createdAt: new Date(),
		username: '',
		userid: '',
		titlename: '',
		titleId: ''
	}
	);
	const categories = ref(['文字', '语录', '歌词', '电影', '诗']);
	let collections = ref<string[]>([]);
	// 方法
	const onBack = () => {
		uni.navigateBack({ delta: 1 });
	};


	// 初始化获取本地数据
	// const getInfo=()=>{
	//     const info=uni.getStorage({
	//         key:'userinfo',
	//         success: (res) => {
	//             console.log(res.data);
	//         }
	//     })

	// }
	// 获取状态机数据
	const User = useCounterStore()

	// 提交数据
	const onNext = async () => {
		try {
			// 1. 同步最新的表单数据
			handleEmit();
			if (!User.userData?.islogin) {//未登录
				uni.showToast({ title: '请先登录', icon: 'none' });
				return;
			}
			// 2. 添加当前时间到 createdAt
			const now = new Date();
			form.value.createdAt = {
				"__type": "Date", // 类型标识，告诉后端这是日期类型
				"iso": now.toISOString() // ISO 时间字符串
			} as unknown as Date; // 用类型断言兼容 Post 接口的 Date 类型定义

			form.value.userid = User.userData.objectId	   //关联用户信息
			form.value.username = User.userData.username
			form.value.avatar = User.userData.avatar

			let res = await createGoods(form.value)//发起请求
			console.log('创建成功', res);
			uni.showToast({ title: '创建成功', icon: 'none' });
			uni.switchTab({
				url: '/pages/mine/mine'
			})
		} catch (err) {
			console.log('创建失败', err);
			uni.showToast({ title: '创建失败', icon: 'none' });
		}
	};

	const chooseImage = () => {
		// 选择图片逻辑
		uni.chooseImage({
			count: 1,
			success: (file) => {
				let temp = file.tempFilePaths[0]//临时路径
				uni.uploadFile({
					url: 'http://1.95.67.194:3000/upload', //此处地址需要时公网IP或真实域名
					filePath: temp,
					name: 'avatar',
					success: (res) => {
						console.log(res.data); //Node中间层下发的数据包
						let url = JSON.parse(res.data).url
						form.value.image = url
						console.log(form);
					},
					fail: (err) => {
						console.error('图片上传失败', err);
						uni.showToast({ title: '图片上传失败', icon: 'none' });
					}
				})
			}
		})
	};

	const openDraft = () => {
		uni.showToast({ title: '打开草稿箱', icon: 'none' });
	};
	// 文集
	let img = ref<string>('')
	const onCollectionChange = (index : number, pic : string) => {
		form.value.titlename = collections.value[index]
		img.value = pic
		console.log(form.value.titlename);
		close();
	};

	// 输入内容绑定
	type cont = 'title' | 'content' | 'author'
	const input = ref<Pick<Post, cont>>({
		title: '',
		content: '',
		author: '',
	})
	const handleEmit = () => {
		form.value.author = input.value.author
		form.value.content = input.value.content
		form.value.title = input.value.title
	}
	//获取对应账号文集名
	onShow(() => {
		console.log(counter.collectedWorks[0]);
		let a = counter.collectedWorks.map(item => item.titlename)
		console.log(a);
		collections.value = [...a]
	})
</script>

<style lang="scss">
	.literature {
		display: block;
		position: relative;
		line-height: 300rpx;
		width: 40%;
		height: 300rpx;
		background-color: #F2F2F2;

		.text-sm {
			position: absolute;
			bottom: -120rpx;
			left: 20rpx;
		}
	}

	// 下分割线
	.divider {
		width: 100%;
		height: 3upx;
		background-color: #e5e7eb;
		margin: 10upx 0upx 10upx 20upx;

		&.cont {
			width: 86%;
			margin: 10upx 60upx 0upx 60upx;
		}
	}

	.divider-cont {
		height: 50upx;
		background-color: #F2F2F2;

		&.big {
			height: 70upx;
		}
	}

	/* 顶部导航 */
	.top-cont {
		height: 60upx;
		background-color: #FFFFFF;
	}

	.cur {
		border-bottom: 4upx solid blue !important;
		padding: 0 0upx !important;
		margin: 0 30upx !important;
		font-weight: 550;
	}


	/* 内容区 */
	.content {
		background-color: #f5f5f5;
	}


	.tab-content {
		background-color: #fff;
		border-radius: 12upx;
	}

	/* 图片上传 */

	.img-cont {
		background-color: #F2F2F2;
		height: 240upx;
	}

	.draft-box {
		position: absolute;
		right: 0upx;
		top: 240upx;
		background-color: #fff;
		padding: 10upx 16upx;
		border-radius: 8upx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		display: flex;
		align-items: center;
		font-size: 26upx;
		color: #666;
	}


	.image-upload {
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;

		.upload-placeholder {
			width: 180upx;
			height: 180upx;
			background-color: #D4D8DB;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #999;
			font-size: 28upx;
		}


	}

	/* 表单通用样式 */

	.form-item {
		display: flex;
		flex-direction: column;

		.input,
		.textarea {
			padding: 20upx;
			background-color: #FFFFFF;
			border-radius: 8upx;
			font-size: 26upx;
			height: 80upx;
			font-size: 32upx;
		}

		.textarea {
			min-height: 250upx;
			margin-left: 40upx;
			font-size: 32upx;
		}
	}

	/* 分类选择 */
	.category-title {
		white-space: nowrap;
	}

	.category-group {
		display: flex;

		flex-wrap: wrap;
		gap: 16upx;
		margin-top: 4upx;
		margin-left: 50upx;

		.category-tag {
			background-color: #f5f5f5;
			padding: 8upx 25upx;
			border-radius: 8upx;
			font-size: 26upx;
			color: #666;
			border: 4upx solid #6C6C6C;

			&.active {
				background-color: #4A4A4A;
				color: #fff;

			}
		}
	}

	/* 开关项 */
	.switch-item {
		height: 80upx;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		background-color: #FFFFFF;

	}

	/* 选择器 */
	.picker-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20upx;
		border-radius: 8upx;
		font-size: 26upx;
		color: #666;
	}

	// 音乐
	.music-upload {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		background-color: #eee;
		border-radius: 12upx;
		padding: 40upx;
		color: #999;
		margin-bottom: 30upx;
	}
</style>